using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Business.PurchaseManagement.Dto;
using Business.Models;
using Microsoft.AspNetCore.Authorization;
using Business.Permissions;

namespace Business.PurchaseManagement
{
    [Authorize(BusinessPermissions.Purchase.Default)]
    public class PurchaseAppService : ApplicationService,IPurchaseAppService
    {
        private const string FormName = "purchase";
        private IRepository<Purchase, Guid> _repository;

        public PurchaseAppService(
            IRepository<Purchase, Guid> repository
            )
        {
            _repository = repository;
        }
        #region 增删改查基础方法

        public async Task<PurchaseDto> Get(Guid id)
        {
            var data = await _repository.GetAsync(id);
            var dto = ObjectMapper.Map<Purchase, PurchaseDto>(data);
            return dto;
        }
        /// <summary>
        /// 显示
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<PurchaseDto>> GetAll(GetPurchaseInputDto input)
        {
            var query = (await _repository.GetQueryableAsync()).WhereIf(!string.IsNullOrWhiteSpace(input.Filter), a => a.Name.Contains(input.Filter)).WhereIf(!string.IsNullOrWhiteSpace(input.Remark),a=>a.Remark.Contains(input.Remark));

            var totalCount = await query.CountAsync();
            var items = await query.OrderBy(input.Sorting ?? "Id")
                       .Skip(input.SkipCount)
                       .Take(input.MaxResultCount)
                       .ToListAsync();

            var dto = ObjectMapper.Map<List<Purchase>, List<PurchaseDto>>(items);
            return new PagedResultDto<PurchaseDto>(totalCount, dto);
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>

        //public async Task<PurchaseDto> DataPost(CreateOrUpdatePurchaseDto input)
        //{
        //    Purchase result = null;
        //    if (!input.Id.HasValue)
        //    {
        //        input.Id = GuidGenerator.Create();
        //        result = await _repository.InsertAsync(ObjectMapper.Map<CreateOrUpdatePurchaseDto, Purchase>(input));
        //    }
        //    else
        //    {
        //        var data = await _repository.GetAsync(input.Id.Value);
        //        result = await _repository.UpdateAsync(ObjectMapper.Map(input, data));
        //    }
        //    return ObjectMapper.Map<Purchase, PurchaseDto>(result);
        //}
        public async Task<PurchaseDto> DataPost(CreateOrUpdatePurchaseDto input)
        {
            Purchase result = null;
            if (!input.Id.HasValue)
            {
                input.Id = GuidGenerator.Create();

                // 映射DTO到实体
                Purchase purchase = ObjectMapper.Map<CreateOrUpdatePurchaseDto, Purchase>(input);

                // 设置时间字段为当前时间
                purchase.Createtime = DateTime.Now; 
                //purchase.Times = DateTime.UtcNow; // 假设Times也需要设置为当前时间，根据实际情况调整

                // 插入实体到数据库
                result = await _repository.InsertAsync(purchase);
            }
            else
            {
                // 更新现有记录的逻辑
                var data = await _repository.GetAsync(input.Id.Value);

                // 映射DTO到现有实体（注意：这里可能需要自定义逻辑来处理只更新非空字段等）
                ObjectMapper.Map(input, data);

                // 如果在更新时也需要设置或更新时间字段，可以在这里添加逻辑
                // 例如，只更新Times字段为当前时间（如果需要的话）
                // data.Times = DateTime.UtcNow;

                // 更新实体到数据库
                result = await _repository.UpdateAsync(data);
            }

            // 映射实体到DTO并返回
            return ObjectMapper.Map<Purchase, PurchaseDto>(result);
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task Delete(List<Guid> ids)
        {
            foreach (var item in ids)
            {
                await _repository.DeleteAsync(item);
            }

        }

     
        #endregion

    }
}